package com.af.monitorModule.controller.log;

import com.af.monitorModule.common.ResultEnum;
import com.af.monitorModule.controller.live.Information;
import com.af.monitorModule.generator.entity.Business;
import com.af.monitorModule.generator.entity.Monitor;
import com.af.monitorModule.generator.mapper.BusinessMapper;
import com.af.monitorModule.generator.service.BusinessService;
import com.af.monitorModule.generator.service.MonitorService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lyz
 */
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/log")
public class CollectionController {

    @Autowired
    private BusinessService businessService;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private MonitorService monitorService;

    private static final Logger logger = LoggerFactory.getLogger(Information.class);

    /**
     * 脚本推送日志信息接口
     * @param monitorId
     * @param logsInfo
     * @return
     */
    @PostMapping("/receive/{monitorId}")
    public JSONObject receive(@PathVariable String monitorId, @RequestBody JSONObject logsInfo){
        String modularName = logsInfo.getString("modular");
        JSONArray logs = logsInfo.getJSONArray("data");
        Monitor byId = monitorService.getById(monitorId);
        List<Business> collect = logs.parallelStream()
                .map(v -> new JSONObject((Map)v).toJavaObject(Business.class))
                .map(v -> v.setModularName(modularName).setSendTime(LocalDateTime.now())
                        .setMonitorId(byId.getId()).setCompanyId(byId.getCompanyId()))
                .collect(Collectors.toList());
        logger.info(monitorId + "-上报了-" + collect.size() + "-条数据");
        return businessService.saveBatch(collect) ? ResultEnum.OK.getResult() : ResultEnum.CREATE_ERROR.getResult();
    }

    /**
     * 获取现有上报日志的分组集合
     * @return
     */
    @GetMapping("/hasGroup")
    public JSONObject getGroup(){
        return ResultEnum.OK.putData(businessMapper.queryValidData());
    }

    /**
     * 根据给定时间区间获取统计响应数据
     * @return
     */
    @SneakyThrows
    @PostMapping("/getStatisticsByDate")
    public JSONObject getStatisticsByDate(@RequestBody JSONObject data){
        int companyId = data.getIntValue("company");
        String modularName = data.getString("modular");
        String times = data.getString("time");
        long btime;
        long etime;
        long min = 0;
        long max = Long.MAX_VALUE;
        if (times.length() > 0){
            String[] beTime = times.split(" ~ ");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            btime = simpleDateFormat.parse(beTime[0]).getTime();
            etime = simpleDateFormat.parse(beTime[1]).getTime();
        }else {
            btime = LocalDateTime.now().plusHours(-24).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            etime = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        }
        String response = data.getString("response");
        if (response.length() > 0){
            switch (response) {
                case "1":
                    min = 0;
                    max = 1999;
                    break;
                case "2":
                    min = 2000;
                    max = 5999;
                    break;
                case "3":
                    min = 6000;
                    max = Long.MAX_VALUE;
                    break;
            }
        }

        return ResultEnum.OK.putData(businessService.allStatistics(companyId,modularName,btime,etime,min,max));
    }

    /**
     * 流加载用查询接口
     * @return
     */
    @GetMapping("/searchLogsStream")
    public JSONObject searchLogsStream(int page,int limit,String search){
        return businessService.selectPage(page,limit,search);
    }

}
